package team526.util;


import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import team526.vo.FileTransferVo;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;

@Component
public class FileSave {
    @Value("${store-path.local-temp-dir}")
    String tempDirPath;

    @Autowired
    RabbitTemplate rabbitTemplate;

    public void saveApi20(String file_storage, byte[] file_bytes) throws IOException {
        File dir = new File(tempDirPath);
        if (!dir.exists()) {
            dir.mkdir();
        }
        String filePathToSave = tempDirPath + File.separator + file_storage;

        //	create the file on server
        File serverFile = new File(filePathToSave);
        BufferedOutputStream bfoStream = new BufferedOutputStream(new FileOutputStream(serverFile));
        bfoStream.write(file_bytes);
        bfoStream.close();

        rabbitTemplate.convertAndSend("amq.fanout", "", filePathToSave);
    }

    public void saveApi2(String file_storage, byte[] file_bytes) {
        FileTransferVo fileTransferVo = new FileTransferVo(file_bytes, file_storage);
        rabbitTemplate.convertAndSend("amq.fanout", "", fileTransferVo);
    }
}
